<template>
  <el-dialog :visible.sync="visible" title="发布设置" width="400px" @close="onCancel">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
      <el-form-item label="定时发布" prop="schedule">
        <el-date-picker
          v-model="form.schedule"
          type="datetime"
          placeholder="选择发布时间"
          :disabled="!form.enableSchedule"
          :picker-options="pickerOptions"
          style="width: 100%"
        />
        <el-switch v-model="form.enableSchedule" style="margin-left: 10px" />
      </el-form-item>
      <el-form-item label="私有发布" prop="private">
        <el-switch v-model="form.private" />
      </el-form-item>
      <el-form-item label="密码保护" prop="password">
        <el-input v-model="form.password" placeholder="访问密码（可选）" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onPublishNow">立即发布</el-button>
      <el-button type="success" @click="onSchedulePublish">定时发布</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  visible: Boolean,
});
const emits = defineEmits(["update:visible", "publish", "schedule-publish"]);

const visible = ref(props.visible);
watch(
  () => props.visible,
  (v) => (visible.value = v)
);
watch(visible, (v) => emits("update:visible", v));

const formRef = ref();
const form = reactive({
  enableSchedule: false,
  schedule: null as Date | null,
  private: false,
  password: "",
});

const rules = {
  schedule: [
    {
      validator: (_: any, value: Date | null, callback: any) => {
        if (form.enableSchedule && (!value || value <= new Date())) {
          callback(new Error("请选择未来的时间"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

const pickerOptions = {
  disabledDate(time: Date) {
    return time.getTime() < Date.now() - 60000; // 允许当前时间+1分钟
  },
};

function onCancel() {
  visible.value = false;
}

function onPublishNow() {
  emits("publish", { ...form, schedule: null });
  visible.value = false;
}

function onSchedulePublish() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      emits("schedule-publish", { ...form });
      visible.value = false;
    } else {
      ElMessage.error("请正确填写定时发布时间");
    }
  });
}
</script>
